//定制请求的实例

import axios from 'axios'
//定义一个变量，记录公共的前缀
const baseURL = 'http://localhost:1111'
const instance = axios.create({
  baseURL,
})

//添加响应拦截器
instance.interceptors.response.use(
  ({ data: result }) => {
    if (result.code !== 200) {
      return Promise.reject(result.message) //异步的状态转化成失败的状态
    }
    return result
  },
  (error) => {
    alert('服务器异常')
    return Promise.reject(error) //异步的状态转化成失败的状态
  },
)

instance.interceptors.request.use(
  (config) => {
    config.headers['Authorization'] = localStorage.getItem('token')
    return config
  },
  (error) => {
    alert('服务器异常')
    return Promise.reject(error) //异步的状态转化成失败的状态
  },
)

export default instance
